﻿namespace Shared.Domain.Abstructs
{
    /// <summary>
    /// 实体基类 包含唯一ID，子类必须要有唯一ID
    /// </summary>
    /// <typeparam name="TId"></typeparam>
    /// <param name="id"></param>
    public abstract class BaseEntity<TId> : IEquatable<BaseEntity<TId>>
    where TId : notnull
    {
        /// <summary>
        /// 唯一Id
        /// </summary>
        public TId Id { get; protected init; }

        public DateTime CreateTime { get; private set; }

        public DateTime UpdateTime { get; private set; }

        protected BaseEntity() { }

        public BaseEntity(TId id)
        {
            this.Id = id;
        }

        #region 相等比较
        public bool Equals(BaseEntity<TId>? other)
        {
            if (other is null) return false;
            if (ReferenceEquals(this, other)) return true;
            return Id.Equals(other.Id);
        }

        public override bool Equals(object? obj) => obj is BaseEntity<TId> other && Equals(other);

        public override int GetHashCode() => Id?.GetHashCode() ?? 0;

        public static bool operator ==(BaseEntity<TId>? left, BaseEntity<TId>? right)
            => Equals(left, right);

        public static bool operator !=(BaseEntity<TId>? left, BaseEntity<TId>? right)
            => !Equals(left, right);
        #endregion
    }
}
